import {
    observable,
    extendObservable,
    computed,
    toJS,
    action
} from '../../libs/mobx.js';
import {
  proxy,
  reqHeader
} from '../../utils/util.js';

let hasNewToken = false;

var CurStore = function(title) {
    let me = this;
    let loginData = wx.getStorageSync('loginData');

    extendObservable(this, Object.assign({
        unionId: '',
        openId: '',
        wxUserInfo: {},
        userInfo: {}
    }, loginData));

    console.log(toJS(this));

    this.setUserInfo = action((userAccountInfo) => {
        let me = this;
        me.userInfo = userAccountInfo;
        hasNewToken = true;
        console.log(toJS(me));
        wx.setStorage({
            key: 'loginData',
            data: toJS(me)
        })
    });
    this.clearUserInfo = action(() => {
      let me = this;
      me.userInfo = {};
      wx.setStorage({
        key: 'loginData',
        data: toJS(me)
      })
    });

    this.isNewUser = function(obj) {
        let me = this;
        wx.request({
          url: `${proxy}/user/v2/thirtPartIsExist`,
            data: obj,
            success: function(res) {
                console.log(res);
                res = res.data;
                if (res.status == 200) {
                    if (res.isExist) {
                        //老用户,登录并跳转
                        wx.request({
                          url: `${proxy}/user/v2/thirtPartlogin`,
                            data: obj,
                            success: function(data) {
                                console.log(data);
                                data = data.data;
                                if (data.status == 200) {
                                    me.userInfo = data.userAccountInfo;
                                    console.log(toJS(me));
                                    hasNewToken = true;
                                    wx.setStorage({
                                        key: 'loginData',
                                        data: toJS(me)
                                    })
                                    wx.hideLoading();
                                    if (obj.callback) {
                                        obj.callback();
                                    }
                                } else {
                                    wx.hideLoading();
                                    console.log(data.message);
                                }
                            }
                        })
                    } else {
                        //新用户绑定手机
                        wx.hideLoading();
                        let pageInfo = JSON.stringify(obj.pageInfo);
                        wx.navigateTo({
                          url: `/pages/login/login?pageInfo=${pageInfo}`,
                        })
                    }
                } else {
                    console.log(res.message);
                }
            }
        })
    }
    this.loginFun = function (handler, pageInfo){
        let me = this;
        wx.login({
            //获取code
            success: function (res) {
                let appid = 'wxfb1c0bd6179a8b50';
                wx.request({
                    url: 'https://node.500px.me/weChat/openId',
                    data: {
                        appid: appid,
                        secret: 'ed8ad1eaf6fa8708088352d950cd0d94',
                        js_code: res.code,
                        grant_type: 'authorization_code'
                    },
                    success: function (result) {
                        console.log(result);//获取openId、session_key
                        let _callback = (resData) => {
                            console.log(resData);
                            if (resData.statusCode == 200) {
                                me.unionId = resData.data.unionId;
                                me.openId = resData.data.openId;
                                //判断该微信用户是否是社区用户
                                me.isNewUser({
                                    callback: handler,
                                    loginId: resData.data.openId,
                                    loginType: 'weixin',
                                    unionId: resData.data.unionId,
                                    pageInfo: pageInfo
                                });
                            } else {
                                console.log('error');
                            }
                        }
                        if (result.statusCode == 200) {
                            wx.getUserInfo({
                                success: function (__res) {
                                    console.log(__res);
                                    me.wxUserInfo = __res.userInfo;

                                    if (!result.data.unionid) {
                                        wx.request({
                                            url: 'https://node.500px.me/weChat/unionId',
                                            data: {
                                                appid: appid,
                                                sessionKey: result.data.session_key,
                                                encryptedData: __res.encryptedData,
                                                iv: __res.iv
                                            },
                                            success: _callback,
                                            fail: function () {
                                                wx.hideLoading();
                                            }
                                        })
                                    } else {
                                        _callback({
                                            statusCode: 200,
                                            data: {
                                                unionId: result.data.unionid,
                                                openId: result.data.openid
                                            }
                                        });
                                    }
                                },
                                fail:function(res){
                                  wx.hideLoading();
                                  console.log(res);
                                }
                            });
                        }else{
                            console.log('error!');
                        }
                    }
                })
            }
        })
    },
        this.validateLogin = action((handler,pageInfo,e) => {
            let me = this;
            
            if (this.userInfo.userId) {
              if (!hasNewToken){
                  //换取新token
                wx.request({
                  url: `${proxy}/wxsoft/applets/refreshToken`,
                  header:reqHeader,
                  data:{
                    userId: this.userInfo.userId,
                    access_token: this.userInfo.access_token
                  },
                  success: function (res) {
                    if (res.statusCode != 200){
                      return;
                   }
                   res = res.data;
                    if (res.status == 200){
                      me.userInfo.access_token = res.access_token;
                      hasNewToken = true;
                      wx.setStorage({
                        key: 'loginData',
                        data: toJS(me)
                      });
                      if (handler instanceof Function) {
                        handler();
                      }
                      
                   }else{
                      console.log(res.message);
                   }
                  },
                  fail:function(e){
                    console.log(e);
                  }
                })

              }else{
                if (handler instanceof Function) {
                  handler();
                }
              }
              
              return;
            }


            let tpl = {};
            if (pageInfo && pageInfo.page) {
                tpl = pageInfo;
            }

            wx.showLoading({
                mask: true,
                title: '验证用户信息',
                success: function() {
                  me.loginFun(handler,tpl,e);
                }
            })
        })
}

export default new CurStore();